package com.ruoyi.web.controller.files.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CommonConstant;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.controller.files.domain.BackChunk;
import com.ruoyi.web.controller.files.domain.BackFilelist;
import com.ruoyi.web.controller.files.domain.vo.CheckChunkVO;
import com.ruoyi.web.controller.files.service.IBackFileService;
import com.ruoyi.web.controller.files.service.IBackFilelistService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 用户报告申请记录Controller
 * 
 * @author csixframework
 * @date 2020-07-20
 */
@Api("文件管理")
@RestController
@RequestMapping("/files/file")
public class BackFileController extends BaseController
{
    @Autowired
    private IBackFileService backFileService;

    @Autowired
    private IBackFilelistService backFileListService;


    @Value("${ruoyi.profile:E:\\data\\ruoyi}")
    String fileBase;


    @ApiOperation(value = "下载文件")
    @PreAuthorize("@ss.hasPermi('tool:file:download')")
    @RequestMapping(value = "/download/manual", method = RequestMethod.GET)
    public void downloadFile1(HttpServletResponse response,Long id) {
        System.out.println(id);
        BackFilelist backFilelist = backFileListService.selectBackFilelistById(id);
        Assert.notNull(backFilelist,"文件找不到！请联系管理员");
        String location = backFilelist.getLocation();
        Assert.notNull(location,"文件未找到，请联系管理员！");
        String fileName = location.substring(location.lastIndexOf("/") + 1);
        String filepath = location.substring(0,location.lastIndexOf("/") + 1);
//        InputStream resourceAsStream= this.getClass().getResourceAsStream("/template/" + fileName);
        FileUtils.downFile(response,filepath,fileName);

    }

    @ApiOperation(value = "删除文件")
    @PreAuthorize("@ss.hasPermi('tool:file:delete')")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteFile(HttpServletResponse response, BackFilelist file) throws Exception{
        System.out.println(file.getId());
        BackFilelist backFilelist = backFileListService.selectBackFilelistById(file.getId());
        Assert.notNull(backFilelist,"文件找不到！请联系管理员");
        String location = backFilelist.getLocation();
        Assert.notNull(location,"文件未找到，请联系管理员！");
        String filepath = location.substring(0,location.lastIndexOf("/") + 1);
        try {
            String uploadPath = RuoYiConfig.getUploadPath();
            int i = backFileListService.deleteBackFilelistById(file.getId());
            // 删除文件及文件夹
            if (StringUtils.isNotBlank(filepath) &&
                    StringUtils.startsWith(filepath,fileBase) &&
                    (filepath.length() - uploadPath.length()) > 1
            ){
                File delFile = new File(filepath);
                if (delFile.exists()){
                    FileUtils.deleteFolders(filepath);
                }
            }
            return toAjax(i);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("删除失败");
            throw new Exception("操作失败");
        }

//        InputStream resourceAsStream= this.getClass().getResourceAsStream("/template/" + fileName);

    }

    /**
     * 查询用户报告申请记录列表
     */
//    @ApiOperation("查询用户报告申请记录列表")
//    @PreAuthorize("@ss.hasPermi('background:report:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(BackFileVO backUserReportVO)
//    {
//        startPage();
//        List<BackFileVO> list = backFileService.selectBackFileList(backUserReportVO);
//        return getDataTable(list);
//    }

    /**
     * 上传文件
     */
    @ApiOperation("上传文件")
    @PreAuthorize("@ss.hasPermi('tool:file:upload')")
    @PostMapping("/upload")
    public AjaxResult postFileUpload(@ModelAttribute BackChunk chunk, HttpServletResponse response)
    {
        int i = backFileService.postFileUpload(chunk, response);
        return toAjax(i);
    }

    /**
     * 检查文件上传状态
     */
    @ApiOperation("检查文件上传状态")
    @PreAuthorize("@ss.hasPermi('tool:file:check')")
    @GetMapping("/upload")
    public CheckChunkVO getFileUpload(@ModelAttribute BackChunk chunk, HttpServletResponse response)
    {
        //查询根据md5查询文件是否存在
        CheckChunkVO fileUpload = backFileService.getFileUpload(chunk, response);
        return fileUpload;
    }

    /**
     * 删除用户报告申请记录
     */
    @ApiOperation("删除文件")
    @PreAuthorize("@ss.hasPermi('tool:file:remove')")
    @Log(title = "用户删除文件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id)
    {
        return toAjax(backFileService.deleteBackFileByIds(id));
    }

    /**
     * 检查文件上传状态
     */
    @ApiOperation("合并文件")
    @PreAuthorize("@ss.hasPermi('tool:file:merge')")
    @PostMapping("/merge")
    public AjaxResult merge(BackFilelist fileInfo)
    {
        int i = backFileService.mergeFile(fileInfo);
        if(i == CommonConstant.UPDATE_EXISTS.intValue()){
            //应对合并时断线导致的无法重新申请合并的问题
            return new AjaxResult(200,"已合并,无需再次提交");
        }
        return toAjax(i);
    }
}
